package org.yang.loginunion.core.wx.miniapp;

import org.apache.commons.lang3.StringUtils;
import org.yang.loginunion.core.LoginClient;
import org.yang.loginunion.core.constants.IdentityType;
import org.yang.loginunion.core.exception.LoginException;
import org.yang.loginunion.core.repository.OauthRepository;
import org.yang.loginunion.core.wx.miniapp.model.MaSession;
import org.yang.loginunion.core.wx.miniapp.model.MaSessionPhoneNumber;
import org.yang.loginunion.core.wx.miniapp.request.IMaRequest;

/**
 *  微信小程序登录
 *
 * @author Billyang
 * @date 2024/8/9 17:53
 */
public class WeixinMiniappClient implements LoginClient {
    private OauthRepository oauthRepository;

    private IMaRequest maRequest;

    public WeixinMiniappClient(OauthRepository oauthRepository, IMaRequest maRequest){
        this.oauthRepository = oauthRepository;
        this.maRequest = maRequest;
    }

    @Override
    public String login(String encryptedData, String iv, String wxcode) {
        if (StringUtils.isAnyBlank(encryptedData, iv, wxcode)) {
            throw new LoginException("缺失参数");
        }

        MaSessionPhoneNumber maSessionPhoneNumber = maRequest.getSessionInfoAndPhoneNumber(encryptedData, iv, wxcode);
        MaSession maSession = maSessionPhoneNumber.getMaSession();

        String mobile = maSessionPhoneNumber.getPhoneNumber();

        String userId = oauthRepository.getUserId(IdentityType.MOBILE, mobile);
        if (userId == null) {
            userId = oauthRepository.registerUser(IdentityType.MOBILE, mobile);
        }

        //绑定用户与openid,unionid的关系
        String openid = maSession.getOpenid();
        oauthRepository.bindOauth(userId, IdentityType.WX_OPENID_MINIAPP, openid, wxcode);
        String unionid = maSession.getUnionid();
        if (StringUtils.isNotBlank(unionid)) {
            oauthRepository.bindOauth(userId, IdentityType.WX_UNIONID, unionid, wxcode);
        }

        return userId;
    }
}
